//
//  ProductDetailViewController.m
//  AmazingShopping
//
//  Created by Tan on 4/21/13.
//  Copyright (c) 2013 Tan Hoang. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "ProductInfoCell.h"
#import "CustomerReviewCell.h"
#import "ProductImageViewController.h"
#import "ProductTechnicalDetailViewController.h"
#import "OrderViewController.h"

@interface ProductDetailViewController ()

@end

@implementation ProductDetailViewController

@synthesize productID, productDetails, tableView, suggestArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    serverPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] serverPath];
    [self getProductDetails];
    if (productDetails != nil) {
        [self.navigationItem setTitle: [NSString stringWithFormat:@"%@",[[productDetails objectAtIndex:0] valueForKey:@"product_name"]]];
    }else{
        [self.navigationItem setTitle:@"Product"];
    }    
    userInfoPath = [(AppDelegate *)[[UIApplication sharedApplication] delegate] userInfoPath];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setTableView:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

- (void)setProductID:(NSInteger *)pid{
    if (pid != productID) {
        productID = pid;
    }
}

- (void)getProductDetails{
    NSString *path = [NSString stringWithFormat:@"%@/get_product_details", serverPath];
    NSURL *url = [NSURL URLWithString:path];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request addPostValue: [NSString stringWithFormat:@"%d", (int) productID] forKey:@"product_id"];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSData *responseData = [request responseData];
        JSONDecoder *jsonDecoder = [[JSONDecoder alloc]initWithParseOptions:JKParseOptionNone];
        productDetails = [jsonDecoder objectWithData:responseData];
        NSArray *relatedProductIds = [[[productDetails objectAtIndex:0] valueForKey:@"related_product"] componentsSeparatedByString:@";"];
        url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/get_product", serverPath]];
        suggestArray = [[NSMutableArray alloc]init];
        for (int i = 0; i < relatedProductIds.count; i++) {
            ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
            [request addPostValue: [NSString stringWithFormat:@"%d", [[relatedProductIds objectAtIndex:i] integerValue]] forKey:@"product_id"];
            [request startSynchronous];
            error = [request error];
            if (!error) {
                responseData = [request responseData];
                NSArray *temp = [jsonDecoder objectWithData:responseData];
                [suggestArray addObjectsFromArray:temp];
            }
        }
        [self.tableView reloadData];
    }else{
        NSLog(@"%@", error);
    }
}

#pragma mark Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = [indexPath row];
    switch (row) {
        case 0:
            return 150.0f;
            break;
        case 1:{
            CGSize maximumSize = CGSizeMake(280, 40);
            UIFont *font = [UIFont fontWithName:@"Helvetica" size:15];
            CGSize stringSize = [[[productDetails objectAtIndex:0] valueForKey:@"product_name"] sizeWithFont:font
                                                  constrainedToSize:maximumSize
                                                      lineBreakMode:UILineBreakModeTailTruncation];
            return (50.0 + stringSize.height);
        }
            
            break;
//        case 2:
//            return 34.0f;
//            break;
        case 2:
            return 34.0f;
            break;
        case 3:
            return 195.0f;
            break;
        case 4:
            return 85.0f;
            break;
        default:
            return 100.0f;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = [indexPath row];
    switch (row) {
        case 0:{
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ImageCell"];
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y + 5, cell.frame.size.width, 140.0f)];
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageData = [[NSData alloc]initWithContentsOfURL: [NSURL URLWithString:[[[productDetails objectAtIndex:0]valueForKey:@"product_images"] objectAtIndex:0]]];
            [imageView setImage:[UIImage imageWithData:imageData]];
            [cell.contentView addSubview:imageView];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }            
            break;
            
        case 1:{
            //Init cell
            static NSString *ProductInfoIndentifier = @"ProductInfoIndentifier";            
            UINib *nib = [UINib nibWithNibName:@"ProductInfoCell" bundle:nil];
            [self.tableView registerNib:nib forCellReuseIdentifier:ProductInfoIndentifier];
            ProductInfoCell *cell = [self.tableView dequeueReusableCellWithIdentifier:ProductInfoIndentifier];
            
            //Set cell data
            [cell setProductName: [[productDetails objectAtIndex:0] valueForKey:@"product_name"]];
            [cell setSellerName:[[productDetails objectAtIndex:0] valueForKey:@"seller_name"]];
            [cell setPrice: [[productDetails objectAtIndex:0] valueForKey:@"product_price"]];
            
            [cell reArrangingFrame];

            //Set cell style
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
            break;
            
//        case 2:{
//            //Init cell
//            static NSString *CustomerReviewIdentifier = @"CustomerReviewIdentifier";
//            UINib *nib = [UINib nibWithNibName:@"CustomerReviewCell" bundle:nil];
//            [self.tableView registerNib:nib forCellReuseIdentifier:CustomerReviewIdentifier];
//            CustomerReviewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CustomerReviewIdentifier];
//            
//            //Set cell data
//            [cell setReviewType:@"Seller Rate"];
//            [cell setRatePoint: [[[productDetails objectAtIndex:0] valueForKey:@"seller_review"] floatValue]];
//            [cell setReviewNumber:[[[productDetails objectAtIndex:0] valueForKey:@"seller_review_number"] integerValue]];
//            
//            //Set cell style
////            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            return cell;
//            
//        }
//            break;
            
        case 2:{
            static NSString *CustomerReviewIdentifier = @"CustomerReviewIdentifier";
            UINib *nib = [UINib nibWithNibName:@"CustomerReviewCell" bundle:nil];
            [self.tableView registerNib:nib forCellReuseIdentifier:CustomerReviewIdentifier];
            CustomerReviewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CustomerReviewIdentifier];
            
            //Set cell data
            [cell setReviewType:@"Product Rate"];
            [cell setRatePoint: [[[productDetails objectAtIndex:0] valueForKey:@"product_review"] floatValue]];
            [cell setReviewNumber:[[[productDetails objectAtIndex:0] valueForKey:@"product_review_number"] integerValue]];
            
            //Set cell style
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
            
        case 3:{
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ScrollViewCell"];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(cell.frame.origin.x + 5, cell.frame.origin.y, cell.frame.size.width, 30)];
            label.font = [UIFont fontWithName:@"Arial-BoldMT" size:15.0];
            label.text = @"Related Items";
            
            UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y + 30, cell.frame.size.width, 160.0)];
            scrollView.showsHorizontalScrollIndicator = NO;
            for (NSInteger i = 0; i < suggestArray.count; i++) {
                ScrollViewCell *productViewCell = [[ScrollViewCell alloc]initWithFrame:CGRectMake(144*i, 0, 144, 160)];
                [productViewCell setImagePath: [[[suggestArray objectAtIndex:i] valueForKey:@"product_images"] objectAtIndex:0]];
                [productViewCell setName: [[suggestArray objectAtIndex:i] valueForKey:@"product_name"]];
                [productViewCell setProductID: (NSInteger *)[[[suggestArray objectAtIndex:i] valueForKey:@"product_id"] intValue]];
                [productViewCell setPrice:[[suggestArray objectAtIndex:i] valueForKey:@"product_price"]];
                [productViewCell setDelegate:self];
                [scrollView addSubview:productViewCell];
                productViewCell = nil;
            }
            
            CGFloat scrollViewHeight = 160;
            CGFloat scrollViewWidth = 0.0f;
            for (UIView *view in scrollView.subviews)
            {
                scrollViewWidth += view.frame.size.width;
            }
            [scrollView setContentSize:(CGSizeMake(scrollViewWidth, scrollViewHeight))];
            [cell.contentView addSubview:label];
            [cell.contentView addSubview:scrollView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return  cell;
        }
            break;
            
        case 4:{
            static NSString *BuyViewCellIdentifier = @"BuyViewCell";
            UINib *nib = [UINib nibWithNibName:@"BuyViewCell" bundle:nil];
            [self.tableView registerNib:nib forCellReuseIdentifier:BuyViewCellIdentifier];
            BuyViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:BuyViewCellIdentifier];
            
            //Set cell data
            cell.delegate =self;
            
            return cell;
        }
            break;
            
        default:{
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ProductDetailCell"];
            cell.textLabel.text = @"No Data";
            return cell;
        }            
            break;
    }
    
}

#pragma mark Table View Delegates

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = [indexPath row];
    switch (row) {
        case 0:{
            ProductImageViewController *nextController = [[ProductImageViewController alloc]init];
            [nextController setImageArray:[[productDetails objectAtIndex:0] valueForKey:@"product_images"]];
            [self.navigationController pushViewController:nextController animated:YES];
        }
            break;
            
        case 1:{
            ProductTechnicalDetailViewController *nextController = [[ProductTechnicalDetailViewController alloc]init];
            [nextController setProductDetails:productDetails];
            [self.navigationController pushViewController:nextController animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark ScrollViewCell Delegate
- (void)didSelectProduct:(NSInteger *)pid{
    ProductDetailViewController *nextController = [[ProductDetailViewController alloc]init];
    [nextController setProductID:pid];
    [self.navigationController pushViewController:nextController animated:YES];
    nextController = nil;
}

#pragma mark BuyViewCell Delegate
- (void)addToCart{
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(160, 0, 30, 40)];
    [imageView setImage: [UIImage imageWithData:imageData]];
    [imageView setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:imageView];
    [UIView animateWithDuration:0.5
                          delay:0
                        options:0
                     animations:^{
                         imageView.frame = CGRectMake(190, 340, 30, 40);
                         imageView.transform = CGAffineTransformMakeRotation(140);
                     }
                     completion:^(BOOL finished){
                         [imageView removeFromSuperview];
                         
                         //Save product info
                         NSMutableDictionary *userData = [[NSMutableDictionary alloc]initWithContentsOfFile:userInfoPath];
                         NSMutableDictionary *productInCart = [[NSMutableDictionary alloc]initWithDictionary:[userData valueForKey:@"ProductInCart"]];
                         if ([productInCart objectForKey:[NSString stringWithFormat:@"%ld", (long)productID]] != nil) {
                             NSInteger qty = [[productInCart valueForKey:[NSString stringWithFormat:@"%ld", (long)productID]] integerValue];
                             qty += 1;
                             [productInCart setValue:[NSString stringWithFormat:@"%ld", (long)qty] forKey:[NSString stringWithFormat:@"%ld", (long)productID]];
                         }else{
                             [productInCart setValue:@"1" forKey:[NSString stringWithFormat:@"%ld", (long)productID]];
                         }
                         
                         //Get qty of cart
                         NSArray *qtyArray = [productInCart allValues];
                         int qty = 0;
                         for (int i = 0; i < qtyArray.count; i++) {
                             qty += [[qtyArray objectAtIndex:i] integerValue];
                         }

                         [[[self.tabBarController.tabBar items] objectAtIndex:2] setBadgeValue:[NSString stringWithFormat:@"%d", qty]];
                         
                         [userData setValue:productInCart forKey:@"ProductInCart"];
                         [userData writeToFile:userInfoPath atomically:YES];
                         
                         NSMutableDictionary *productData = [[NSMutableDictionary alloc]init];
                         [productData setValue:[[productDetails objectAtIndex:0] valueForKey:@"product_id"] forKey:@"ID"];
                         [productData setValue:[[productDetails objectAtIndex:0] valueForKey:@"product_name"] forKey:@"Name"];
                         [productData setValue:[[productDetails objectAtIndex:0] valueForKey:@"product_price"] forKey:@"Price"];
                         [productData setValue:imageData forKey:@"Image"];
                         [productData setValue:@"1" forKey:@"Qty"];
                         
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"AddedProductInCart" object:self userInfo:productData];
                     }];
    
    
}

- (void)buy{
    OrderViewController *nextController = [[OrderViewController alloc]init];
    [self.navigationController pushViewController:nextController animated:YES];
    nextController = nil;
}

@end
